package cn.itsource.org.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.itsource.org.domain.User;
import cn.itsource.org.mapper.UserMapper;
import cn.itsource.org.query.UserQuery;
import cn.itsource.org.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public void save(User user) {
     if(user.getId() == null){
         //动态生成盐值
         String s = RandomUtil.randomString(20);
         user.setSalt(s);
         //设置密码
         user.setPassword(SecureUtil.md5(user.getPassword()+ user.getSalt()));
         userMapper.insert(user);
     }else {
         userMapper.updateByPrimaryKeySelective(user);
     }
    }

    @Override
    @Transactional
    public int deleteByPrimaryKey(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public User selectByPrimaryKey(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<User> pageInfo(UserQuery userQuery) {
        PageHelper.startPage(userQuery.getCurrentPage(),userQuery.getPageSize());
        List<User> users = userMapper.selectAllByQuery(userQuery);
        return new PageInfo<User>(users);
    }

    @Override
    public void deleteByCollection(List<User> users) {
        userMapper.deleteByConllection(users);
    }

    @Override
    public Boolean exist(User user) {
        //根据用户名去数据库查询用户对象
        User userByDB = userMapper.getByName(user.getUserName());
        if (user.getId() == null) {
            return userByDB == null;
        }else{
            //根据用户名去数据库查询
            if (userByDB == null) {
                return true;
            }else{
                return userByDB.getId().equals(user.getId());
            }
            //值为0： OK的
            //值不为0： 1个       拿到这个对象的值，和前端的id进行匹配，
            // 如果相等ok，如果不相等，就不ok
        }
    }


}
